package com.biostime.springdraw.common.wechat;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.common.web.BaseController;
import com.biostime.springdraw.modules.sd.service.HttpRequestService;
import com.biostime.springdraw.modules.sd.service.SignService;

/**
 * 校验服务器
 * @author chenweicheng
 * @version 2016-03-30
 */
@Controller
@RequestMapping(value = "wx")
public class WechatServlet extends BaseController {

	
	
	/**
	 * 检验服务器有有效性
	 * 注意：（尚未做签名校验，待完善）
	 */
	@SuppressWarnings("unused")
	@ResponseBody
	@RequestMapping(value ="check")
	public String  check(HttpServletRequest request) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		return echostr;
	}
	
	@ResponseBody
	@RequestMapping(value ="createMenu")
	public String createMenu(){
		String body = "{\"button\": [{\"type\": \"click\", \"name\": \"测试\",  \"key\": \"V1001_TODAY_MUSIC\"}, { \"name\": \"菜单\", \"sub_button\": [{\"type\": \"view\",  \"name\": \"妈妈100\", \"url\": \"http://springdraw.howjoin.com/front?fromSystem=mama100\" },{\"type\": \"view\",  \"name\": \"合生元\", \"url\": \"http://springdraw.howjoin.com/front\" }]}]}";
		return HttpRequestService.sendPost("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=OeqhYFLkfivLBfiz6rIvvH2eTGkTSMJOCd0672T90eSQekV5INjLDaWRjOOCxcSXXTPanHURMdMUfdmGUWNN60zQc0nnh019sKOel94du_Xs9fVBVM1y_3wWxxgofXbtTITgADAODO", 
				body);
	}
	
	@ResponseBody
	@RequestMapping(value ="/")
	public String news(HttpServletRequest request,HttpServletResponse response){
		
		 Map<String, String[]> params = request.getParameterMap();  
	        String queryString = "";  
	        for (String key : params.keySet()) {  
	            String[] values = params.get(key);  
	            for (int i = 0; i < values.length; i++) {  
	                String value = values[i];  
	                queryString += key + "=" + value + "&";  
	            }  
	        }  		
		return "hello world"; 
	}

	@RequestMapping(value ="jssdkConifg")	
	@ResponseBody
	public HashMap<String,Object> jssdkConifg(HttpServletRequest request){
		
		long timestamp = new Date().getTime();
		String noncestr = String.valueOf(new Date().getTime());		
		String jsticket = null;
		String appId = null;
		String mySign = null;
		
		byte[] sendBytes1 = HttpRequestService.sendGet(BiostimeWechat.Jsticket, "from=ismart");
		byte[] sendBytes2 = HttpRequestService.sendGet(BiostimeWechat.AppID, "from=ismart");
		
		try {
			
			String jsticketJson=new String( sendBytes1 ,"UTF-8"); 
			String appIdJson=new String( sendBytes2 ,"UTF-8"); 
			String url =  request.getRequestURL() + (StringUtils.isEmpty(request.getQueryString()) ? "" : ("?"+request.getQueryString()));
			
			HashMap<String,String> m = (HashMap<String, String>) BiostimeWechat.Api.toMap(jsticketJson);	
			m = (HashMap<String, String>) BiostimeWechat.Api.toMap(appIdJson);
						
			jsticket = m.get("jsticket");
			appId = m.get("appId");
			
	        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
	        parameters.put("url", url);  
	        parameters.put("jsapi_ticket", jsticket);
	        parameters.put("timestamp", timestamp);  
	        parameters.put("noncestr", noncestr);
	        String characterEncoding = "UTF-8";  
	        mySign = SignService.createSign(characterEncoding,parameters);
					
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("appId", appId);
		map.put("timestamp", timestamp);
		map.put("nonceStr", noncestr);
		map.put("signature",mySign);		
		
		return map; 
	}
	
	

}